package ajaxjs.data.user;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigInteger;
import java.security.*;

import ajaxjs.lang.servletHandler;

public class Cookies {
	private final static String key = "#frank1983";
	
	public HttpServletRequest request;
	public HttpServletResponse response;
	
	@servletHandler
	public Cookies(HttpServletRequest request, HttpServletResponse response){
		this.request = request;
		this.response = response;
	}
	
	public void setId(String id){
		String secretId = md5_encode(id + key);
		setCookie(id + "#" + secretId);
	}
	
	public void setCookie(String value){
//		String host = request.getServerName();  
		// 保存密码到Cookie，注意需要加密一下  
//		System.out.println(value);
		Cookie cookie = new Cookie("id", value);  
		cookie.setPath(request.getContextPath());  
//		cookie.setDomain(host);  
		cookie.setMaxAge(99999999);  
		response.addCookie(cookie);
	}
	
	private static String md5_encode(String plaintext) {
		MessageDigest m = null;
		try {
			m = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		m.reset();
		m.update(plaintext.getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1, digest);
		String hashtext = bigInt.toString(16);
		
		// Now we need to zero pad it if you actually want the full 32 chars.
		while (hashtext.length() < 32) {
			hashtext = "0" + hashtext;
		}

		return hashtext;
	}
	
	private boolean isValid(String cookieValue){
		if(cookieValue ==  null)return false;
		
		String[] arr = cookieValue.split("#");
		
		if(arr.length < 2){
			System.out.println("解析 Cookie value 不正确");
			return false;
		}
		
		String id = arr[0], secretId = arr[1];
		
		return isValid(id, secretId);
	}
	private boolean isValid(String id, String md5_str){
		String testStr = md5_encode(id + key);
		
		return md5_str.equals(testStr);
	}
	
	public static String getCookie(HttpServletRequest request, String key) {
		Cookie[] cookies = request.getCookies();
		String value = null;

		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key))
					value = cookie.getValue();
				// out.println(cookie.getName());
			}
		}

		return value;
	}
	
	public boolean isValid(){
		String cookieValue = Cookies.getCookie(request, "id");
		return isValid(cookieValue);
	}
}
